package com.itboye.ihomebank.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CameraPopupWindow;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UploadImage;
import com.itboye.ihomebank.util.UploadImage.OnUploadlistener;
import com.itboye.ihomebank.util.XImageLoader;

public class ActivityRenZheng extends BaseOtherActivity implements Observer, OnUploadlistener {

	CameraPopupWindow cameraPopupWindow;
	int type;
	ImageView fangchanzheng, weituoshu;
	private String picture_name;
	private String fileName02;
	private String localSelectPath02;
	private static final int REAL_PHONE = 101;
	private static final int REAL_PICTURE = 102;
	HousePresenter housePresenter;
	TextView card_tijiao;
	private String uid;
	private String houseNo;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.fangchanzheng:
			type = 1;
			cameraPopupWindow = new CameraPopupWindow(this, this);
			cameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.weituoshu:
			type = 2;
			cameraPopupWindow = new CameraPopupWindow(this, this);
			cameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.open_camera:
			opencamera();
			break;
		case R.id.pick_image:
			pickImage();
			break;
		case R.id.card_tijiao:
			uid=SPUtils.get(this, null, SPContants.USER_ID, "")+"";
			String imgFangChanZheng=fangchanzheng.getTag()+"";
			String imgWeiTuoShu=weituoshu.getTag()+"";
			String[] imgUri=new String[]{imgFangChanZheng,imgWeiTuoShu};
			UploadImage.getInstance().execute(imgUri, "property", this,houseNo);//property 房产证
			UploadImage.getInstance().execute(imgUri, "agent", this,houseNo);//委托书
//			housePresenter.fangYuanRenZheng(uid, houseNo, pass, msg);
			break;
		default:
			break;
		}
	}

	void opencamera() {

		/**
		 * 打开照相机
		 */
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, REAL_PHONE);

		} else {
			Toast.makeText(ActivityRenZheng.this, "请确认已经插入SD卡", 2000).show();
		}

	}

	void pickImage() {
		Intent intent2 = new Intent();
		intent2.setType("image/*");// 可选择图片视频
		// 修改为以下两句代码
		intent2.setAction(Intent.ACTION_PICK);
		intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
		startActivityForResult(intent2, REAL_PICTURE);
	}

	void setImageCamera(Intent data) {

		String sdStatus01 = Environment.getExternalStorageState();
		if (!sdStatus01.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.i("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}
		picture_name = android.text.format.DateFormat.format("yyyyMMdd_hhmmss",
				Calendar.getInstance(Locale.CHINA)) + ".jpg";
		Bundle bundle02 = data.getExtras();
		Bitmap bitmap02 = (Bitmap) bundle02.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
		// SavePicInLocal(bitmap);
		FileOutputStream b02 = null;
		File file02 = new File("/sdcard/Image/");
		file02.mkdirs();// 创建文件夹
		fileName02 = "/sdcard/Image/" + picture_name;

		try {
			b02 = new FileOutputStream(fileName02);
			bitmap02.compress(Bitmap.CompressFormat.JPEG, 100, b02);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b02.flush();
				b02.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// Bitmap bit03 = BitmapFactory.decodeFile(fileName02);
		if (type == 1) {
			XImageLoader.load("file://" + fileName02, fangchanzheng);
			fangchanzheng.setTag(fileName02);
			// fangchanzheng.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		} else if (type == 2) {
			XImageLoader.load("file://" + fileName02, weituoshu);
			fangchanzheng.setTag(fileName02);
			// weituoshu.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		}
		cameraPopupWindow.dismiss();
	}

	void setPickImg(Intent data) {
		/**
		 * 当选择的图片不为空的话，在获取到图片的途径
		 */
		Uri selectedImage04 = data.getData();
		localSelectPath02 = null;
		localSelectPath02 = getRealPathFromURI(selectedImage04);
		if (type == 1) {
			XImageLoader.load("file://" + localSelectPath02, fangchanzheng);
			fangchanzheng.setTag(localSelectPath02);
			// fangchanzheng.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		} else if (type == 2) {
			XImageLoader.load("file://" + localSelectPath02, weituoshu);
			fangchanzheng.setTag(localSelectPath02);
			// weituoshu.setImageBitmap(bt04); // 把图片显示在ImageView控件上
		}

		cameraPopupWindow.dismiss();
	}

	/**
	 * 该方法用于获取文件的真实路径从URI 从相机拍摄
	 */
	private String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REAL_PHONE:// 相机
				setImageCamera(data);
				break;
			case REAL_PICTURE:
				setPickImg(data);
				break;
			}
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_renzhengfangyuan;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		housePresenter = new HousePresenter(this);
		houseNo=getIntent().getStringExtra("house_no");
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.fangYuanRenZheng_success) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == HousePresenter.fangYuanRenZheng_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

	@Override
	public void OnSuccess(ArrayList<AvatarDataBeans> resultData) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnError(String resultData) {
		// TODO Auto-generated method stub
		
	}

}
